﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Configuration;
using Zhongjiu.Common.DbFirst;

namespace Zhongjiu.ConsoleApp
{
  public class DbFirst
  {

    public static void GenerateCodes()
    {
      var IsGenerateCode =ConfigurationManager.AppSettings["IsGenerateCode"].ToBool();
      if (IsGenerateCode)
      {
        Console.WriteLine("从数据库生成代码：1");
        var isMuti = ConfigurationManager.AppSettings["MutiDBEnabled"].ToBool();
        var conns = ConfigurationManager.ConnectionStrings;
        var listConns = new List<ConnectionConfig>();
        for (int i = 1; i < conns.Count; i++)
        {
          var m = conns[i];
          listConns.Add(new ConnectionConfig
          {
            ConfigId = m.Name,
            ConnectionString = m.ConnectionString,
            DbType = DbType.MySql,
            IsAutoCloseConnection = true,
            // Check out more information: https://github.com/anjoy8/Zhongjiu/issues/122
            //IsShardSameThread = false,
            //AopEvents = new AopEvents
            //{
            //  OnLogExecuting = (sql, p) =>
            //  {
            //    if (Appsettings.app(new string[] { "AppSettings", "SqlAOP", "Enabled" }).ToBool())
            //    {
            //      if (Appsettings.app(new string[] { "AppSettings", "SqlAOP", "OutToLogFile", "Enabled" }).ToBool())
            //      {
            //        Parallel.For(0, 1, e =>
            //        {
            //          MiniProfiler.Current.CustomTiming("SQL：", GetParas(p) + "【SQL语句】：" + sql);
            //          LogLock.OutSql2Log("SqlLog", new string[] { GetParas(p), "【SQL语句】：" + sql });

            //        });
            //      }
            //      if (Appsettings.app(new string[] { "AppSettings", "SqlAOP", "OutToConsole", "Enabled" }).ToBool())
            //      {
            //        ConsoleHelper.WriteColorLine(string.Join("\r\n", new string[] { "--------", "【SQL语句】：" + GetWholeSql(p, sql) }), ConsoleColor.DarkCyan);
            //      }
            //    }
            //  },
            //},
            MoreSettings = new ConnMoreSettings()
            {
              //IsWithNoLockQuery = true,
              IsAutoRemoveDataCache = true
            },
            // 从库
            //SlaveConnectionConfigs = listConfig_Slave,
            // 自定义特性
            ConfigureExternalServices = new ConfigureExternalServices()
            {
              EntityService = (property, column) =>
              {
                if (column.IsPrimarykey && property.PropertyType == typeof(int))
                {
                  column.IsIdentity = true;
                }
              }
            },
            InitKeyType = InitKeyType.Attribute
          });
        }
        var sqlScope = new SqlSugarScope(listConns);
        var rootPath = Environment.CurrentDirectory.Remove(Environment.CurrentDirectory.IndexOf("Zhongjiu.ConsoleApp"));
        listConns.ForEach(c =>
        {
          sqlScope.ChangeDatabase(c.ConfigId);
          Console.WriteLine($"库{c.ConfigId}-Model层生成：{SqlSugarDbFirst.Create_Model_ClassFileByDBTalbe(sqlScope, c.ConfigId, rootPath + "Zhongjiu.Model\\AutoGenerate", "Zhongjiu.Model", isMuti)}完成； ");
          
          Console.WriteLine($"库{c.ConfigId}-IRepositorys层生成：{SqlSugarDbFirst.Create_IRepository_ClassFileByDBTalbe(sqlScope, c.ConfigId, rootPath + "Zhongjiu.IRepository\\AutoGenerate", "Zhongjiu.IRepository", isMuti)}完成；");
          
          Console.WriteLine($"库{c.ConfigId}-Repository层生成：{SqlSugarDbFirst.Create_Repository_ClassFileByDBTalbe(sqlScope, c.ConfigId, rootPath + "Zhongjiu.Repository\\AutoGenerate", "Zhongjiu.Repository", isMuti)}完成；");
          ////不是每个表都要对应有service；
          //Console.WriteLine($"库{c.ConfigId}-IServices层生成：{SqlSugarDbFirst.Create_IServices_ClassFileByDBTalbe(sqlScope, c.ConfigId, rootPath + "Zhongjiu.IServices\\AutoGenerate", "Zhongjiu.IServices", isMuti)}完成；");
          //Console.WriteLine($"库{c.ConfigId}-Services层生成：{SqlSugarDbFirst.Create_Services_ClassFileByDBTalbe(sqlScope, c.ConfigId, rootPath + "Zhongjiu.Services\\AutoGenerate", "Zhongjiu.Services", isMuti)}完成；");
        });

        Console.WriteLine("从数据库生成代码结束");
      }
    }
  }
}
